package com.etung.iot.demo.storage.conTriggerStorage;

import com.etung.iot.demo.constant.CommonConstant;
import com.etung.iot.demo.dao.RealDataMapper;
import com.etung.iot.demo.modles.ConditionStorageEntity;
import com.etung.iot.demo.modles.RealData;
import com.etung.iot.demo.storage.constorage.ConditionRuleEnum;
import com.etung.iot.demo.storage.constorage.TargetTypeEnum;
import com.etung.iot.demo.utils.BigDecimalUtil;
import com.etung.iot.demo.utils.RedisUtil;
import com.etung.iot.demo.utils.StorageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 前置触发
 * 其他变量发生改变，存储当前变量值，当前变量值也许未发生改变
 */
@Component
public class PreTriggerStoreRule {
    @Autowired
    private PreConditionStorageUtil conditionStorageUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RealDataMapper realDataMapper;
    @Autowired
    private StorageUtil storageUtil;

    public void saveTargetVariantValue(RealData monitorVarRealData) {
        boolean isNeedSave = false;
        String imei = monitorVarRealData.getImei();
        int monitorVarId = monitorVarRealData.getVarId();
        List<ConditionStorageEntity> conditionStorageRuleList = conditionStorageUtil.getConditionStorageRule(imei, monitorVarId);
        if (conditionStorageRuleList != null && conditionStorageRuleList.size() > 0) {
            for (ConditionStorageEntity conditionStorageEntity : conditionStorageRuleList) {
                if (!StringUtils.isEmpty(monitorVarRealData.getValue())) {
                    BigDecimal monitorValue = BigDecimalUtil.getBigDecimal(monitorVarRealData.getValue());
                    if (conditionStorageEntity.getTargetType() == TargetTypeEnum.SCALE_TYPE.getValue()) {
                        isNeedSave = storageUtil.scaleTypeJudge(monitorValue, conditionStorageEntity);
                    } else if (conditionStorageEntity.getTargetType() == TargetTypeEnum.VAR_TYPE.getValue()) {
                        isNeedSave = storageUtil.varTypeJudge(imei, monitorValue, conditionStorageEntity);
                    } else {
                        isNeedSave = isChanged(monitorVarRealData);
                    }
                    if (isNeedSave) {
                        if (conditionStorageEntity.getRuleType() == ConditionRuleEnum.TRIGGER.getValue()) {
                            saveAllConVar(monitorVarRealData, conditionStorageEntity);
                        } else { //周期触发
                            periodTrigger(monitorVarRealData, conditionStorageEntity);
                        }
                    }
                }
            }
        }
    }

    /**
     * 判断当前变量是否发生过变化
     *
     * @param monitorVarRealData
     * @return
     */
    private boolean isChanged(RealData monitorVarRealData) {
        RealData lastRealData = conditionStorageUtil.getChangeTypeLastRealData(monitorVarRealData.getImei(), monitorVarRealData.getVarId());
        if (lastRealData == null || lastRealData.isValueChanged(monitorVarRealData)) {
            return true;
        }
        return false;
    }

    /**
     * 周期触发判断是否保存
     *
     * @param conditionStorageEntity
     */
    private void periodTrigger(RealData realData, ConditionStorageEntity conditionStorageEntity) {
        String varIdList = conditionStorageEntity.getVarIdList();
        if (!StringUtils.isEmpty(varIdList)) {
            String[] split = varIdList.split(",");
            for (String varIdStr : split) {
                int varId = Integer.parseInt(varIdStr);
                //判断是否保存过了
                long lastStoreTimestamp = conditionStorageUtil.getLastStoreTimestamp(conditionStorageEntity.getImei(), varId);
                if (realData.getTime().getTime() - lastStoreTimestamp > conditionStorageEntity.getCycle() * 1000) {
                    saveData(realData, varId);
                }
            }
        }
    }

    /**
     * 保存所有的目标变量值
     *
     * @param conditionStorageEntity
     */
    private void saveAllConVar(RealData realData, ConditionStorageEntity conditionStorageEntity) {
        String varIdList = conditionStorageEntity.getVarIdList();
        if (!StringUtils.isEmpty(varIdList)) {
            String[] split = varIdList.split(",");
            for (String varIdStr : split) {
                int varId = Integer.parseInt(varIdStr);
                //判断是否保存过了
                long lastStoreTimestamp = conditionStorageUtil.getLastStoreTimestamp(conditionStorageEntity.getImei(), varId);
                if (lastStoreTimestamp != realData.getTime().getTime()) {
                    saveData(realData, varId);
                }
            }
        }
    }


    /**
     * 保存数据
     *
     * @param realData
     */
    private void saveData(RealData realData, int varId) {
        conditionStorageUtil.saveLastStoreTimestamp(realData.getImei(), varId, realData.getTime().getTime());
        String cacheKey = CommonConstant.REAL_DATA_CACHE_PREFIX + realData.getImei() + "_" + varId;
        try {
            RealData cacheData = (RealData) redisUtil.get(cacheKey);
            if (cacheData != null) {
                RealData newData = new RealData();
                newData.setImei(realData.getImei());
                newData.setVarId(varId);
                newData.setTime(realData.getTime());
                newData.setValue(cacheData.getValue());
                realDataMapper.insert(newData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
